package org.aplombh.java.leetcode.all;

public class _19删除链表的倒第N个节点 {
}

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

// 快慢指针
class Solution19_1 {
    public ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode p = new ListNode();
        p.next = head;

        ListNode l = p;
        ListNode r = p;

        for (int i = 0; i < n; i++) {
            if (r == null)
                return null;
            r = r.next;
        }

        while (r.next!=null){
            l = l.next;
            r = r.next;
        }

        ListNode q = l.next;
        l.next = l.next.next;

        return p.next;
    }
}

// 递归
class Solution19_2 {
    public ListNode removeNthFromEnd(ListNode head, int n) {

        int level = level(head, n);

        // 删除头节点
        if(level == n)
            return head.next;
        return head;
    }

    private int level(ListNode node, int n) {
        if(node == null)
            return 0;
        int num = level(node.next, n);
        if(num == n)
            node.next = node.next.next;
        return num + 1;
    }
}